package com.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.*;
import com.example.service.*;
import com.example.util.DateUtil;
import com.example.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 订单Controller控制器
 */
@RestController
@RequestMapping("/my/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private IProductService productService;
    @Autowired
    private IProductHealthService productHealthService;
    @Autowired
    private IProductHealthItemService productHealthItemService;

    /**
     * 创建订单，返回订单号
     * @param token
     * @return
     */
    @RequestMapping("/create")
    @Transactional
    public R create(@RequestBody Order order, @RequestHeader(value = "token") String token) {
        // 通过token获取openid
        System.out.println("token=" + token);
        System.out.println("order=" + order);

        // 添加订单到数据库
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        if (claims != null) {
            System.out.println("openid=" + claims.getId());
            order.setUserId(claims.getId());
        }
        order.setOrderNo("JAVA" + DateUtil.getCurrentDateStr());
        order.setCreateDate(new Date());

        // 获取订单商品详情
        OrderDetail[] goods = order.getGoods();
        orderService.save(order);

        // 遍历订单商品详情，保存商品详情并更新库存
        for (OrderDetail orderDetail : goods) {
            // 设置订单详情的主表ID
            orderDetail.setMId(order.getId());
            orderDetailService.save(orderDetail);

            // 根据 itemType 判断是普通商品还是健康商品
            if ("normal".equals(orderDetail.getItemType())) {
                // 处理普通商品，直接查找产品表，减少库存
                Product product = productService.getById(orderDetail.getGoodsId());
                if (product != null && product.getStock() >= orderDetail.getGoodsNumber()) {
                    // 减库存
                    product.setStock(product.getStock() - orderDetail.getGoodsNumber());
                    productService.updateById(product);
                } else {
                    // 库存不足，抛出异常或返回错误
                    throw new RuntimeException("商品 " + product.getName() + " 库存不足");
                }
            } else if ("health".equals(orderDetail.getItemType())) {
                // 处理健康商品，先查找健康商品组合表，再查找 t_product_health_items 关联的商品
                ProductHealth productHealth = productHealthService.getById(orderDetail.getGoodsId());
                if (productHealth != null) {
                    // 查询健康商品组合下的商品项
                    LambdaQueryWrapper<ProductHealthItem> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(ProductHealthItem::getHealthId, productHealth.getId());
                    List<ProductHealthItem> healthItems = productHealthItemService.list(queryWrapper);

                    for (ProductHealthItem healthItem : healthItems) {
                        // 查找每个商品的详细信息
                        Product product = productService.getById(healthItem.getGoodId());
                        if (product != null && product.getStock() >= orderDetail.getGoodsNumber()) {
                            // 减库存
                            product.setStock(product.getStock() - orderDetail.getGoodsNumber());
                            productService.updateById(product);
                        } else {
                            // 库存不足，抛出异常或返回错误
                            throw new RuntimeException("商品 " + product.getName() + " 库存不足");
                        }
                    }
                } else {
                    // 健康商品组合不存在，抛出异常
                    throw new RuntimeException("健康商品组合不存在");
                }
            }
        }

        // 返回订单号
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("orderNo", order.getOrderNo());
        return R.ok(resultMap);
    }


//    @RequestMapping("/create")
//    @Transactional
//    public R create(@RequestBody Order order, @RequestHeader(value = "token")String token){
//        // 通过token获取openid
//        System.out.println("token="+token);
//        System.out.println("order="+order);
//        // 添加订单到数据库
//        Claims claims = JwtUtils.validateJWT(token).getClaims();
//        if(claims!=null){
//            System.out.println("openid="+claims.getId());
//            order.setUserId(claims.getId());
//        }
//        order.setOrderNo("JAVA"+ DateUtil.getCurrentDateStr());
//        order.setCreateDate(new Date());
//
//        OrderDetail[] goods = order.getGoods();
//        orderService.save(order);
//        // 添加订单详情到数据库
//        for(int i=0;i<goods.length;i++){
//            OrderDetail orderDetail=goods[i];
//            orderDetail.setMId(order.getId());
//            orderDetailService.save(orderDetail);
//        }
//        Map<String,Object> resultMap=new HashMap<>();
//        resultMap.put("orderNo",order.getOrderNo());
//        return R.ok(resultMap);
//    }

    /**
     * 订单查询 type值 0 全部订单 1 待付款 2 待收货 3 退回退款
     */
    @RequestMapping("/list")
    public R list(Integer type, Integer page,Integer pageSize){
        System.out.println("type="+type);
        List<Order> orderList=null;
        Map<String,Object> resultMap=new HashMap<>();
        Page<Order> pageOrder = new Page<>(page,pageSize);
        if(type==0){
//                orderList=orderService.list(new QueryWrapper<Order>().orderByDesc("id"));
            Page<Order> orderResult = orderService.page(pageOrder,new QueryWrapper<Order>().orderByDesc("id"));
            System.out.println("总记录数"+orderResult.getTotal());
            System.out.println("总页数"+orderResult.getPages());
            System.out.println("当前页数据"+orderResult.getRecords());
            orderList=orderResult.getRecords();
            resultMap.put("total",orderResult.getTotal());
            resultMap.put("totalPage",orderResult.getPages());
        }else {
//                orderList=orderService.list(new QueryWrapper<Order>().eq("status",type).orderByDesc("id"));
            Page<Order> orderResult = orderService.page(pageOrder,new QueryWrapper<Order>().eq("status",type).orderByDesc("id"));
            System.out.println("总记录数"+orderResult.getTotal());
            System.out.println("总页数"+orderResult.getPages());
            System.out.println("当前页数据"+orderResult.getRecords());
            orderList=orderResult.getRecords();
            resultMap.put("total",orderResult.getTotal());
            resultMap.put("totalPage",orderResult.getPages());
        }
        resultMap.put("orderList",orderList);
        return R.ok(resultMap);
    }

    // 取消订单接口
    @RequestMapping("/cancel")
    public R cancelOrder(@RequestBody Map<String, Object> params) {
        Integer orderId = (Integer) params.get("orderId");
        Order order = orderService.getById(orderId);

        if (order == null) {
            return R.error("订单不存在");
        }

        // 判断订单状态，确保只能取消待付款订单
        if (order.getStatus() != 1) {
            return R.error("只能取消待付款的订单");
        }

        // 执行订单删除操作
        boolean result = orderService.removeById(orderId);
        orderDetailService.remove(new QueryWrapper<OrderDetail>().eq("mid", orderId));

        if (result) {
            return R.ok("订单已取消");
        } else {
            return R.error("取消订单失败，请重试");
        }
    }
    @PostMapping("/confirmed")
    public R confirmedOrder(@RequestBody Map<String, Object> params) {
        Integer orderId = (Integer) params.get("orderId");
        Order order = orderService.getById(orderId);

        if (order == null) {
            return R.error("订单不存在");
        }

        // 检查订单状态，确保只能确认待收货的订单
        if (order.getStatus() != 2) {
            return R.error("只能确认待收货的订单");
        }

        // 更新订单状态为已收货
        order.setStatus(5);
        orderService.updateById(order);
        return R.ok("确认收货成功");
    }
    @PostMapping("/return")
    public R returndOrder(@RequestBody Map<String, Object> params) {
        Integer orderId = (Integer) params.get("orderId");
        Order order = orderService.getById(orderId);

        if (order == null) {
            return R.error("订单不存在");
        }

        // 检查订单状态，确保只能确认待收货的订单
        if (order.getStatus() != 2) {
            return R.error("请确认信息");
        }

        // 更新订单状态为已收货
        order.setStatus(4);
        orderService.updateById(order);
        return R.ok("申请成功");
    }
}

